<?php

namespace Lshorz\LaravelConfig\Middleware;

use Closure;
use Illuminate\Http\Request;
use Lshorz\LaravelConfig\CfgManager;

class CfgVerify
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param string $identifier
     * @param string $driver
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next, $identifier = null, $driver = null)
    {
        $cfg = app(CfgManager::class);
        if ($driver) $cfg = $cfg->driver($driver);

        if (!$cfg->init($identifier)->valid()) {
            if ($request->wantsJson()) {
                return response()->json(['code' => 500, 'message' => "Config [{$cfg->getIdentifier()}] Error"]);
            } else {
                abort(500, "Config [{$cfg->getIdentifier()}] Error");
            }
        }
        return $next($request);
    }
}
